package me.info.common;

import static cn.hutool.json.JSONUtil.isJson;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.lang3.StringUtils;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Amber L
 * @version v0.0.1
 * @desc
 * @date 2020/12/25 17:13
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MockJs {
  /** Javascript执行引擎 */
  public static final ScriptEngine MOCK_JS_ENGINE;
  /** mockjs的资源路径 */
  private static final String MOCK_JS_PATH = "js/mock-min.js";

  static {
    MOCK_JS_ENGINE = new ScriptEngineManager().getEngineByName("js");
    try (InputStream mockJs = MockJs.class.getClassLoader().getResourceAsStream(MOCK_JS_PATH);
        InputStreamReader reader = new InputStreamReader(mockJs)) {
      MOCK_JS_ENGINE.eval(reader);
    } catch (ScriptException | IOException e) {
      log.error("执行MockJs错误", e);
    }
  }

  public static String mock(String template) {
    String result = StringUtils.trimToEmpty(template);
    if (isJson(result)) {
      try {
        result = MOCK_JS_ENGINE.eval("JSON.stringify(Mock.mock(" + result + "))").toString();
      } catch (ScriptException e) {

        log.error("执行Mock.mock错误", e);
      }
    }
    return result;
  }
}
